<template>
  <div class="selector-wrap">
    <span :class="['select-header', disabled?'t3': '']" @click="open=!disabled">
      {{selectedValue}} <i class="iconfont icon-small-arrow-right"/>
    </span>
    <mu-popup position="bottom" popupClass="demo-popup-bottom" :open="open" @close="close">
      <mu-list class=" text-center">
          <div class="popup-title">{{title}}</div>
           <mu-divider/>
          <template v-for="(item, i) in options">
            <mu-list-item :title="item[label]" :key="'only' + i" @click="handleItemClick(item)">
            </mu-list-item>
            <mu-divider/>
          </template>
      </mu-list>
      <mu-divider/>
      <div class="popup-footer" @click="close">取消</div>
    </mu-popup>
    </div>
</template>

<script>
export default {
  name: 'selector',
  data () {
    return {
      selectedValue: '请选择',
      open: false
    }
  },
  props: {
    options: {
      type: Array,
      default: []
    },
    title: {
      type: String,
      default: '请选择'
    },
    label: {
      type: [String, Number, Boolean]
    },
    disabled: {
      type: Boolean,
      default: false
    },
    defaultValue: {
      type: [Number, String],
      default: ''
    }
  },
  watch: {
    defaultValue: {
      handler (newval){
        // if (!newval) {
        //   return
        // }
        let selectedOption = this.options.filter(v => String(newval) === v[this.label])
        if(selectedOption.length > 0) {
          this.selectedValue = String(newval)
        } else {
          this.selectedValue = '请选择'
        }
      },
      immediate: true
    },
    options: {
      handler (newval) {
        let selectedOption = newval.filter(v => String(this.defaultValue) === v[this.label])
        if(selectedOption.length > 0) {
          this.selectedValue = String(this.defaultValue)
        } else {
          this.selectedValue = '请选择'
        }
      }
    }
  },
  methods: {
    close () {
      this.open = false
    },
    handleItemClick (item) {
      this.selectedValue = item[this.label]
      this.$emit('selectchange', item)
      this.close()
    }
  }
}
</script>

<style lang="less">
@import '../common/css/vars.less';
.demo-popup-bottom {
  width: 100%;
  max-height: 300px;
  overflow-y: scroll;
  .mu-item-title {
    text-align: center;
    color: @color-primary;
  }
}
.select-header {
  .iconfont {
    vertical-align:middle;
  }
}
.popup-title {
  text-align: center;
  line-height: 40px;
  color: #999;
}
.popup-footer {
  text-align: center;
  line-height: 40px;
  color: #666;
  border-top:8px solid #f2f2f2;
}
</style>
